import Taro from '@tarojs/taro'
import React, { useCallback, useState } from 'react';
import { dataFetch } from '@pier88health/p8h-common';
import { View, Text, Image } from '@tarojs/components'
import { useSelector, useDispatch } from 'react-redux'
import withWebLogin from '@HOC/withWebLogin'
import UserAvatar from '@COMPONENTS/User/UserAvatar'
import WxAuthButton from '@COMPONENTS/Button/WxAuthButton'
import LoginVerifyBtn from '@COMPONENTS/Button/LoginVerifyBtn'
import i18n from '@I18N'
import profileActions from '@ACTIONS/profile'
import authActions from '@ACTIONS/auth'
import { NAME_STATUS, GENDER_ENUM } from '@CONSTANTS/profile'
import Navigate from '@NAVIGATION/navigateManager'
import { getPlatform } from '@UTILS/common'
import { Analytic_Type } from '@CONSTANTS/analytic'
import Images from '@ASSET/Images'
import DBConfig from '@CONFIG/DBConfig'
import style from './ProfileHeader.module.scss'

const isProd = DBConfig.baseUrl.indexOf('//wmp') > 0

const HeaderLoginWrapped = ({
  canGetUserInfo, onGetUserInfo, showLogin, onClickHeader, children
}) => {
  if (canGetUserInfo) {
    return (
      <WxAuthButton onGetUserInfo={onGetUserInfo}>
        {children}
      </WxAuthButton>
    )
  }
  return (
    <LoginVerifyBtn
      showLogin={showLogin}
      className={style.loginBtn}
      eventId={Analytic_Type.num_my_login.eventId}
      onClick={onClickHeader}
    >
      {children}
    </LoginVerifyBtn>
  )
}

const ProfileHeader = ({ language, showLogin }) => {
  const [weChatAvatarUrl, setWeChatAvatarUrl] = useState('')
  const profile = useSelector(state => state.profile)
  const { isVisitor, user } = profile
  const {
    UserPersonal: { DisplayName } = {}, NameStatus, State, City, District
  } = user || {}

  const dispatch = useDispatch()
  const { dispatchUpdateProfileByWeChat } = profileActions
  const { dispatchLogout } = authActions
  const updateProfile = useCallback(params => dispatch(dispatchUpdateProfileByWeChat(params)), [dispatch, dispatchUpdateProfileByWeChat])
  const logOut = useCallback(params => dispatch(dispatchLogout(params)), [dispatch, dispatchLogout])

  const onClickHeader = useCallback(
    e => {
      e?.stopPropagation?.()
      Taro.tracker.trackEvent(Analytic_Type.num_my_login.eventId)
      Navigate.editBaseInfo()
    },
    []
  )

  const onGetUserInfo = useCallback(userInfo => {
    if (!userInfo) {
      Navigate.editBaseInfo()
      return
    }
    const {
      country, avatarUrl, nickName, gender
    } = userInfo
    setWeChatAvatarUrl(avatarUrl)
    const genderArr = ['', GENDER_ENUM.Male, GENDER_ENUM.Female]
    updateProfile({
      Country: country,
      IconUrl: avatarUrl,
      Name: nickName,
      Gender: genderArr[gender]
    })
  }, [setWeChatAvatarUrl, updateProfile])

  const onClickExit = useCallback(e => {
    e?.stopPropagation?.()
    if (isVisitor) {
      Navigate.authPage()
      return
    }
    logOut?.(true)
  }, [isVisitor, logOut])

  const { isWX, isWeb } = getPlatform()
  const isEmptyName = NameStatus === NAME_STATUS.Empty
  const canGetUserInfo = isWX && !isVisitor && isEmptyName
  const userData = isVisitor ? {} : user
  const userName = isVisitor ? i18n.profile.visitor_name() : DisplayName?.[language]
  const showLogOut = !isProd && !(isWeb && isVisitor)
  const address = dataFetch.getAddress({
    State, City, District, language
  }).split(' ')

  return (
    <View className={style.container}>
      <HeaderLoginWrapped
        canGetUserInfo={canGetUserInfo}
        onGetUserInfo={onGetUserInfo}
        showLogin={showLogin}
        onClickHeader={onClickHeader}
      >
        <View className={style.headerContainer}>
          <UserAvatar data={userData} defaultUrl={weChatAvatarUrl} />

          <View className={style.headerRight}>
            <View className={style.userInfo}>
              <Text className={style.userName}>
                {userName}
              </Text>
              <Text className={style.addressText}>{address}</Text>
            </View>
            <Image src={Images.arrow.form} className={style.rightArrow} />
          </View>
        </View>
      </HeaderLoginWrapped>
      {showLogOut && <Text onClick={onClickExit} className={style.logOutText}>{isVisitor ? '登录' : '退出' }</Text>}
    </View>
  )
}

export default withWebLogin(ProfileHeader)
